<template>
    <div class="common-layout">
        <el-container>
            <el-main style="padding-bottom: 80px;">
                <el-form ref="transferFormRef" :model="transferForm" :rules="rules" label-width="120px">
                    <el-card class="card-block">
                        <template #header>
                            <span class="card-title">基础信息</span>
                        </template>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="调拨单号" prop="transferNo">
                                    <el-input v-model="transferForm.transferNo" placeholder="自动获取系统编号"
                                        class="readonly-input" readonly>
                                        <template #append>
                                            <el-button @click="generateTransferNo" :loading="generatingCode">
                                                自动生成
                                            </el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="调拨申请日期" prop="transferApplicationDate">
                                    <el-date-picker v-model="transferForm.transferApplicationDate" type="date"
                                        value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="调拨类型" prop="transferTypeId">
                                    <el-select v-model="transferForm.transferTypeId" placeholder="请选择" clearable
                                        style="width: 100%">
                                        <el-option v-for="item in transferTypeOptions" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="经办人" prop="handler">
                                    <el-input v-model="transferForm.handler" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="调出仓库" prop="outboundWarehouseId">
                                    <el-select v-model="transferForm.outboundWarehouseId" placeholder="请选择" filterable
                                        clearable style="width: 100%" @change="handleOutboundWarehouseChange">
                                        <el-option v-for="item in warehouseOptions" :key="item.warehouseId"
                                            :label="item.warehouseName" :value="item.warehouseId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="调入仓库" prop="inboundWarehouseId">
                                    <el-select v-model="transferForm.inboundWarehouseId" placeholder="请选择" filterable
                                        clearable style="width: 100%" @change="handleInboundWarehouseChange">
                                        <el-option v-for="item in warehouseOptions" :key="item.warehouseId"
                                            :label="item.warehouseName" :value="item.warehouseId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="备注">
                                    <el-input v-model="transferForm.remark" type="textarea" :rows="3"
                                        placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>

                    <el-card class="card-block">
                        <template #header>
                            <div class="detail-header">
                                <span class="card-title">调拨明细</span>
                                <div class="detail-actions">
                                    <el-button type="primary" @click="openProductDialog">新增</el-button>
                                    <el-button type="danger" plain :disabled="!selectedDetailRows.length"
                                        @click="removeSelectedDetails">
                                        移除
                                    </el-button>
                                </div>
                            </div>
                        </template>
                        <el-table ref="detailTableRef" :data="transferDetails" border style="width: 100%"
                            highlight-current-row @selection-change="handleDetailSelectionChange"
                            empty-text="请先通过“新增”按钮选择货品">
                            <el-table-column type="selection" width="50" />
                            <el-table-column type="index" label="序号" width="60" />
                            <el-table-column prop="productName" label="货品名称" min-width="160" />
                            <el-table-column prop="productCode" label="货品编号" min-width="140" />
                            <el-table-column label="规格型号" min-width="120">
                                <template #default="{ row }">
                                    {{ row.specificationModel || row.productUnit || '--' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="unitName" label="单位" width="90" />
                            <el-table-column prop="productTypeName" label="货品类型" width="120" />
                            <el-table-column prop="outboundCurrentStock" label="调出仓当前库存" width="140" align="right">
                                <template #default="{ row }">
                                    {{ row.outboundCurrentStock ?? 0 }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="inboundCurrentStock" label="调入仓当前库存" width="140" align="right">
                                <template #default="{ row }">
                                    {{ row.inboundCurrentStock ?? 0 }}
                                </template>
                            </el-table-column>
                            <el-table-column label="* 调拨数量" width="130">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.transferQuantity" :min="1" :precision="0"
                                        controls-position="right" placeholder="必填" :value-on-clear="1"
                                        @change="updateDetailAmount(row)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="* 调拨单价" width="140">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.transferUnitPrice" :min="0.01" :precision="2"
                                        controls-position="right" placeholder="必填" :value-on-clear="0.01"
                                        @change="updateDetailAmount(row)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="调拨金额" width="120">
                                <template #default="{ row }">
                                    ¥{{ row.transferAmount?.toFixed(2) || '0.00' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="160">
                                <template #default="{ row }">
                                    <el-input v-model="row.remark" placeholder="可填写补充说明" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80" fixed="right">
                                <template #default="scope">
                                    <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="detail-summary" v-if="transferDetails.length">
                            <span>调拨种类：{{ totalProductKinds }}</span>
                            <span>调拨数量：{{ totalTransferQuantity }}</span>
                            <span>总金额：¥{{ totalTransferAmount.toFixed(2) }}</span>
                        </div>
                    </el-card>
                </el-form>
            </el-main>
        </el-container>

        <el-dialog v-model="productDialogVisible" title="添加货品" width="1200px">
            <el-form :inline="true" :model="productSearchForm" class="product-search-form">
                <el-form-item>
                    <el-input v-model="productSearchForm.keyword" placeholder="请输入货品编号/名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button @click="resetProductSearch">重置</el-button>
                    <el-button type="primary" @click="searchProducts">查询</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="productList" border height="420" v-loading="productTableLoading"
                @selection-change="handleProductSelectionChange">
                <el-table-column type="selection" width="50" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="productCode" label="货品编号" min-width="140" />
                <el-table-column prop="productName" label="货品名称" min-width="160" />
                <el-table-column prop="producttypeName" label="货品类型" min-width="120" />
                <el-table-column label="规格" min-width="120">
                    <template #default="{ row }">
                        {{ row.productUnit || row.mainUnit || row.unitDisplay || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="单位" min-width="120">
                    <template #default="{ row }">
                        {{ row.productspecification || row.productSpecification || row.specification || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="productInmoney" label="入库单价" min-width="100" />
                <el-table-column prop="inventoryCurrtnumber" label="当前库存" min-width="100" />
            </el-table>

            <div class="product-pagination">
                <el-pagination v-model:current-page="productPagination.pageindex"
                    v-model:page-size="productPagination.pagesize" :page-sizes="[10, 20, 50]"
                    layout="total, sizes, prev, pager, next" :total="productPagination.total"
                    @size-change="handleProductSizeChange" @current-change="handleProductCurrentChange" />
            </div>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="productDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmProductSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <div class="fixed-footer">
            <div class="footer-content">
                <el-button @click="goBack">关闭</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import myaxios from '@/http/MyAxios'

const router = useRouter()
const route = useRoute()

const transferFormRef = ref<FormInstance>()
const generatingCode = ref(false)
const pageMode = ref<'create' | 'edit' | 'copy'>('create')
const currentTransferId = ref<number | null>(null)
const copySourceId = ref<number | null>(null)
const TRANSFER_EDIT_CACHE_KEY = 'TRANSFER_EDIT_CACHE'

const transferForm = reactive({
    transferNo: '',
    transferApplicationDate: '',
    transferTypeId: null as number | null,
    outboundWarehouseId: null as number | null,
    inboundWarehouseId: null as number | null,
    handler: '',
    remark: '',
})

const rules = {
    transferNo: [{ required: true, message: '调拨单号不能为空', trigger: 'blur' }],
    transferApplicationDate: [{ required: true, message: '请选择调拨申请日期', trigger: 'change' }],
    transferTypeId: [{ required: true, message: '请选择调拨类型', trigger: 'change' }],
    outboundWarehouseId: [{ required: true, message: '请选择出库仓库', trigger: 'change' }],
    inboundWarehouseId: [{ required: true, message: '请选择入库仓库', trigger: 'change' }],
}

interface WarehouseItem {
    warehouseId: number
    warehouseName: string
}

interface TransferDetailItem {
    lineId: string
    transferDetailId?: number
    productId: string | number
    productName: string
    productCode: string
    specificationModel?: string
    productUnit?: string
    unitName: string
    productTypeName?: string
    outboundCurrentStock?: number
    inboundCurrentStock?: number
    transferQuantity: number | null | undefined
    transferUnitPrice: number
    transferAmount: number
    remark: string
    lowerLimit?: number
}

interface ProductListItem {
    productId: string | number
    productCode: string
    productName: string
    producttypeName?: string
    productSpecification?: string
    productspecification?: string
    specification?: string
    productUnit?: string
    inventoryCurrtnumber?: number
    productInmoney?: number
    unitDisplay?: string
    mainUnit?: string
    [key: string]: any
}

const isWarehouseSelected = (value: unknown) => value !== null && value !== undefined && value !== ''

interface TransferTypeOption {
    label: string
    value: number
}

const warehouseOptions = ref<WarehouseItem[]>([])
const transferTypeOptions = ref<TransferTypeOption[]>([])
const fallbackTransferTypeOptions: TransferTypeOption[] = [{ label: '货品调拨', value: 1 }]
const transferDetails = ref<TransferDetailItem[]>([])
const selectedDetailRows = ref<TransferDetailItem[]>([])
const saving = ref(false)
const isEditMode = computed(() => pageMode.value === 'edit')

const productDialogVisible = ref(false)
const productTableLoading = ref(false)
const productList = ref<ProductListItem[]>([])
const selectedProducts = ref<ProductListItem[]>([])

const productSearchForm = reactive({
    keyword: '',
})

const productPagination = reactive({
    pageindex: 1,
    pagesize: 10,
    total: 0,
})

const buildLineId = (seed?: string | number) => {
    if (seed !== undefined && seed !== null && seed !== '') {
        return `line_${seed}`
    }
    return `line_${Date.now()}_${Math.random()}`
}

const resolveNumberValue = (...candidates: any[]): number | null => {
    for (const candidate of candidates) {
        if (candidate === undefined || candidate === null || candidate === '') continue
        const num = Number(candidate)
        if (!Number.isNaN(num)) return num
    }
    return null
}

const normalizeDateValue = (value?: string | null) => {
    if (!value) return ''
    if (typeof value !== 'string') return ''
    if (value.includes('T')) {
        return value.split('T')[0]
    }
    return value.slice(0, 10)
}

const equalIgnoreCase = (a?: string, b?: string) => {
    if (!a || !b) return false
    return a.trim().toLowerCase() === b.trim().toLowerCase()
}

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
    const now = new Date()
    const segments = (rule?.timeRule || '')
        .split(',')
        .map((s: string) => s.trim().toUpperCase())
        .filter(Boolean)
        .sort((a: string, b: string) => {
            const idxA = TIME_SEGMENT_ORDER.indexOf(a)
            const idxB = TIME_SEGMENT_ORDER.indexOf(b)
            if (idxA === -1 && idxB === -1) return 0
            if (idxA === -1) return 1
            if (idxB === -1) return -1
            return idxA - idxB
        })
    const timePart = segments
        .map((seg: string) => {
            switch (seg) {
                case 'YYYY': return String(now.getFullYear())
                case 'YY': return String(now.getFullYear()).slice(-2)
                case 'MM': return pad(now.getMonth() + 1)
                case 'DD': return pad(now.getDate())
                case 'HH': return pad(now.getHours())
                case 'MI': return pad(now.getMinutes())
                case 'SS': return pad(now.getSeconds())
                default: return ''
            }
        })
        .join('')
    const serialLength = Number(rule?.serialLength ?? 3)
    const serial = '1'.padStart(serialLength > 0 ? serialLength : 3, '0')
    return `${rule?.codePrefix || ''}${timePart}${serial}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
    try {
        const res = await myaxios.get('/api/Number/GenerateNumber', {
            params: { targetCode, targetName },
        })
        if (res?.data?.code === 200 && res?.data?.data) {
            return String(res.data.data)
        }
        throw new Error(res?.data?.message || '生成编号失败')
    } catch (err) {
        console.warn(`[numbering] GenerateNumber 接口不可用 (${targetCode})，尝试规则生成`, err)
        const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
            params: { targetCode, targetName },
        })
        const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
        if (list.length > 0) {
            return buildCodeFromRule(list[0])
        }
        throw new Error('未找到对应的编号规则，请先配置编号规则')
    }
}

const generateTransferNo = async () => {
    if (generatingCode.value) return
    generatingCode.value = true
    try {
        transferForm.transferNo = await requestNumber('Transfer', '调拨单')
        ElMessage.success('编号生成成功')
    } catch (error: any) {
        ElMessage.error(error?.message || '生成编号失败')
    } finally {
        generatingCode.value = false
    }
}

const loadWarehouses = async () => {
    try {
        const res = await myaxios.get('/api/Warehousing/GetWarehouse')
        if (res.data.code === 200 || res.data.success) {
            warehouseOptions.value = (res.data.data || []).map((item: any) => ({
                warehouseId: item.warehouseId,
                warehouseName: item.warehouseName,
            }))
        }
    } catch (error) {
        console.error('获取仓库列表失败:', error)
    }
}

const applyEditCache = () => {
    const cache = sessionStorage.getItem(TRANSFER_EDIT_CACHE_KEY)
    if (!cache) return
    try {
        const cached = JSON.parse(cache)
        const cachedDate = normalizeDateValue(cached.transferApplicationDate || cached.transferApplyDate)
        if (cachedDate) {
            transferForm.transferApplicationDate = cachedDate
        }
        transferForm.transferNo = cached.transferNo || transferForm.transferNo
        const cachedTypeId = resolveNumberValue(cached.transferTypeId, cached.transferType?.value)
        if (cachedTypeId !== null) {
            transferForm.transferTypeId = cachedTypeId
        }
        const cachedOutbound = resolveNumberValue(cached.outboundWarehouseId, cached.outWarehouseId)
        if (cachedOutbound !== null) {
            transferForm.outboundWarehouseId = cachedOutbound
        }
        const cachedInbound = resolveNumberValue(cached.inboundWarehouseId, cached.inWarehouseId)
        if (cachedInbound !== null) {
            transferForm.inboundWarehouseId = cachedInbound
        }
        transferForm.handler = cached.handler || transferForm.handler
        transferForm.remark = cached.remark || transferForm.remark
    } catch (error) {
        console.warn('解析编辑缓存失败:', error)
    } finally {
        sessionStorage.removeItem(TRANSFER_EDIT_CACHE_KEY)
    }
}

const normalizeTransferDetailItem = (detail: any, options?: { isCopy?: boolean }): TransferDetailItem => {
    const detailId = Number(detail.transferDetailId ?? detail.detailId ?? 0)
    const productId = resolveNumberValue(detail.productId, detail.goodsId, detail.productID) ?? 0
    return {
        lineId: buildLineId(options?.isCopy ? undefined : detailId || undefined),
        transferDetailId: options?.isCopy ? 0 : detailId,
        productId,
        productName: detail.productName || '',
        productCode: detail.productCode || '',
        specificationModel: detail.specificationModel || detail.productUnit || detail.specification || '',
        productUnit: detail.productUnit || '',
        unitName: detail.unitName || detail.unit || '',
        productTypeName: detail.productTypeName || detail.producttypeName || '',
        outboundCurrentStock: Number(detail.outboundCurrentStock ?? detail.currentStock ?? 0),
        inboundCurrentStock: Number(detail.inboundCurrentStock ?? detail.targetStock ?? 0),
        transferQuantity: Number(detail.transferQuantity ?? detail.quantity ?? 0),
        transferUnitPrice: Number(detail.transferUnitPrice ?? detail.inboundPrice ?? detail.transferPrice ?? 0),
        transferAmount: Number(detail.transferAmount ?? detail.amount ?? detail.totalAmount ?? 0),
        remark: detail.remark || '',
        lowerLimit: Number(detail.lowerLimit ?? 0),
    }
}

const loadTransferDetailForForm = async (
    transferId: number | string,
    options?: { isCopy?: boolean }
) => {
    if (!transferId) return
    try {
        const res = await myaxios.get('/api/Transfer/GetTransferDetail', {
            params: { transferId },
        })
        if (res.data?.code === 200) {
            const data = res.data?.data || {}
            if (options?.isCopy) {
                currentTransferId.value = null
            } else {
                currentTransferId.value = resolveNumberValue(data.transferId, transferId)
            }

            const transferDate = normalizeDateValue(data.transferApplyDate || data.transferApplicationDate)
            transferForm.transferNo = options?.isCopy ? '' : (data.transferNo || transferForm.transferNo)
            transferForm.transferApplicationDate = transferDate || ''
            const typeId = resolveNumberValue(data.transferTypeId, data.transferType?.value)
            transferForm.transferTypeId = typeId
            if (transferForm.transferTypeId === null && data.transferType) {
                const matchedType = transferTypeOptions.value.find(
                    (item) =>
                        equalIgnoreCase(item.label, data.transferType) ||
                        equalIgnoreCase(item.label, data.transferTypeName),
                )
                if (matchedType) {
                    transferForm.transferTypeId = matchedType.value
                }
            }
            transferForm.outboundWarehouseId = resolveNumberValue(
                data.outWarehouseId,
                data.outboundWarehouseId,
                data.sourceWarehouseId,
            )
            transferForm.inboundWarehouseId = resolveNumberValue(
                data.inWarehouseId,
                data.inboundWarehouseId,
                data.targetWarehouseId,
            )
            if (
                transferForm.outboundWarehouseId === null &&
                data.outboundWarehouseName &&
                warehouseOptions.value.length
            ) {
                const matchedOutbound = warehouseOptions.value.find((item) =>
                    equalIgnoreCase(item.warehouseName, data.outboundWarehouseName),
                )
                if (matchedOutbound) {
                    transferForm.outboundWarehouseId = matchedOutbound.warehouseId
                }
            }
            if (
                transferForm.inboundWarehouseId === null &&
                data.inboundWarehouseName &&
                warehouseOptions.value.length
            ) {
                const matchedInbound = warehouseOptions.value.find((item) =>
                    equalIgnoreCase(item.warehouseName, data.inboundWarehouseName),
                )
                if (matchedInbound) {
                    transferForm.inboundWarehouseId = matchedInbound.warehouseId
                }
            }
            transferForm.handler = data.handler || ''
            transferForm.remark = data.remark || ''

            const details = Array.isArray(data.transferDetails)
                ? data.transferDetails
                : Array.isArray(data.details)
                    ? data.details
                    : []
            transferDetails.value = details.map((item: any) => normalizeTransferDetailItem(item, options))
            selectedDetailRows.value = []
        }
    } catch (error) {
        console.error('获取调拨单详情失败:', error)
        ElMessage.error('获取调拨单详情失败')
    }
}

const clearForm = () => {
    transferForm.transferNo = ''
    transferForm.transferApplicationDate = ''
    transferForm.transferTypeId = null
    transferForm.outboundWarehouseId = null
    transferForm.inboundWarehouseId = null
    transferForm.handler = ''
    transferForm.remark = ''
    transferDetails.value = []
    selectedDetailRows.value = []
}

const initPage = async () => {
    const transferIdParam = resolveNumberValue(route.query.transferId)
    const copyFromParam = resolveNumberValue(route.query.copyFrom)

    clearForm()
    copySourceId.value = null

    if (transferIdParam) {
        pageMode.value = 'edit'
        currentTransferId.value = transferIdParam
        applyEditCache()
        await loadTransferDetailForForm(transferIdParam)
    } else if (copyFromParam) {
        pageMode.value = 'copy'
        copySourceId.value = copyFromParam
        await loadTransferDetailForForm(copyFromParam, { isCopy: true })
    } else {
        pageMode.value = 'create'
        currentTransferId.value = null
        copySourceId.value = null
        transferForm.transferNo = ''
        transferForm.transferApplicationDate = ''
        transferForm.transferTypeId = null
        transferForm.outboundWarehouseId = null
        transferForm.inboundWarehouseId = null
        transferForm.handler = ''
        transferForm.remark = ''
    }
}

const handleOutboundWarehouseChange = () => {
    if (isWarehouseSelected(transferForm.outboundWarehouseId) && isWarehouseSelected(transferForm.inboundWarehouseId) &&
        transferForm.outboundWarehouseId === transferForm.inboundWarehouseId) {
        ElMessage.warning('入库仓库和出库仓库不能为同一仓库!')
        transferForm.inboundWarehouseId = null
    }
    updateDetailStocks()
}

const handleInboundWarehouseChange = () => {
    if (isWarehouseSelected(transferForm.outboundWarehouseId) && isWarehouseSelected(transferForm.inboundWarehouseId) &&
        transferForm.outboundWarehouseId === transferForm.inboundWarehouseId) {
        ElMessage.warning('入库仓库和出库仓库不能为同一仓库!')
        transferForm.inboundWarehouseId = null
        return
    }
    updateDetailStocks()
}

const updateDetailStocks = async () => {
    if (!isWarehouseSelected(transferForm.outboundWarehouseId) || !isWarehouseSelected(transferForm.inboundWarehouseId)) {
        transferDetails.value.forEach(item => {
            item.outboundCurrentStock = 0
            item.inboundCurrentStock = 0
        })
        return
    }

    for (const detail of transferDetails.value) {
        try {
            // 获取调出仓库存
            let outboundStock = 0
            let inboundStock = 0
            let lowerLimit = 0

            // 获取调出仓库存
            try {
                const outboundRes = await myaxios.get('/api/Inventory/GetInventoryPage', {
                    params: {
                        productCode: detail.productCode,
                        warehouseId: transferForm.outboundWarehouseId,
                        pageIndex: 1,
                        pageSize: 10,
                    },
                })
                if (outboundRes.data?.code === 200) {
                    const inventoryList = outboundRes.data?.data?.data || []
                    // 从列表中查找匹配的货品（通过productCode或productId）
                    const inventory = inventoryList.find((item: any) =>
                        item.productId === Number(detail.productId) ||
                        item.productCode === detail.productCode
                    )
                    if (inventory) {
                        outboundStock = Number(inventory.currentStock ?? inventory.inventoryCurrtnumber ?? inventory.currtnumber ?? 0)
                        lowerLimit = Number(inventory.lowerLimit ?? 0)
                    }
                }
            } catch (e) {
                console.warn('获取调出仓库存失败:', e)
            }

            // 获取调入仓库存
            try {
                const inboundRes = await myaxios.get('/api/Inventory/GetInventoryPage', {
                    params: {
                        productCode: detail.productCode,
                        warehouseId: transferForm.inboundWarehouseId,
                        pageIndex: 1,
                        pageSize: 10,
                    },
                })
                if (inboundRes.data?.code === 200) {
                    const inventoryList = inboundRes.data?.data?.data || []
                    // 从列表中查找匹配的货品（通过productCode或productId）
                    const inventory = inventoryList.find((item: any) =>
                        item.productId === Number(detail.productId) ||
                        item.productCode === detail.productCode
                    )
                    if (inventory) {
                        inboundStock = Number(inventory.currentStock ?? inventory.inventoryCurrtnumber ?? inventory.currtnumber ?? 0)
                    }
                }
            } catch (e) {
                console.warn('获取调入仓库存失败:', e)
            }

            detail.outboundCurrentStock = outboundStock
            detail.inboundCurrentStock = inboundStock
            detail.lowerLimit = lowerLimit
        } catch (error) {
            console.error('获取库存失败:', error)
            detail.outboundCurrentStock = 0
            detail.inboundCurrentStock = 0
        }
    }
}

const openProductDialog = () => {
    if (!isWarehouseSelected(transferForm.outboundWarehouseId) || !isWarehouseSelected(transferForm.inboundWarehouseId)) {
        transferFormRef.value?.validateField(['outboundWarehouseId', 'inboundWarehouseId'])
        return
    }
    productDialogVisible.value = true
    searchProducts()
}

const searchProducts = async () => {
    productTableLoading.value = true
    try {
        const res = await myaxios.get('/api/Product/GetProduct', {
            params: {
                Pageindex: productPagination.pageindex,
                PageSize: productPagination.pagesize,
                ProductName: productSearchForm.keyword,
                number: 1,
            },
        })
        if (res.data?.success || res.data?.code === 200) {
            const payload = res.data.data || {}
            productList.value = payload.data || payload.items || []
            productPagination.total = payload.listCount || productList.value.length || 0
        }
    } catch (error) {
        console.error('搜索货品失败:', error)
        ElMessage.error('搜索货品失败')
    } finally {
        productTableLoading.value = false
    }
}

const resetProductSearch = () => {
    productSearchForm.keyword = ''
    productPagination.pageindex = 1
    searchProducts()
}

const handleProductSelectionChange = (selection: ProductListItem[]) => {
    selectedProducts.value = selection
}

const handleProductSizeChange = (val: number) => {
    productPagination.pagesize = val
    productPagination.pageindex = 1
    searchProducts()
}

const handleProductCurrentChange = (val: number) => {
    productPagination.pageindex = val
    searchProducts()
}

const confirmProductSelection = async () => {
    if (selectedProducts.value.length === 0) {
        ElMessage.warning('请选择货品!')
        return
    }

    for (const product of selectedProducts.value) {
        const exists = transferDetails.value.some(d => d.productId === product.productId)
        if (exists) {
            ElMessage.warning(`货品 ${product.productName} 已存在，跳过`)
            continue
        }

        let outboundStock = 0
        let inboundStock = 0
        let lowerLimit = 0

        if (isWarehouseSelected(transferForm.outboundWarehouseId) && isWarehouseSelected(transferForm.inboundWarehouseId)) {
            try {
                // 使用 GetInventoryPage API 分别获取调出仓和调入仓的库存
                // 获取调出仓库存
                try {
                    const outboundRes = await myaxios.get('/api/Inventory/GetInventoryPage', {
                        params: {
                            productCode: product.productCode,
                            warehouseId: transferForm.outboundWarehouseId,
                            pageIndex: 1,
                            pageSize: 10,
                        },
                    })
                    if (outboundRes.data?.code === 200) {
                        const inventoryList = outboundRes.data?.data?.data || []
                        // 从列表中查找匹配的货品（通过productCode或productId）
                        const inventory = inventoryList.find((item: any) =>
                            item.productId === Number(product.productId) ||
                            item.productCode === product.productCode
                        )
                        if (inventory) {
                            outboundStock = Number(inventory.currentStock ?? inventory.inventoryCurrtnumber ?? inventory.currtnumber ?? 0)
                            lowerLimit = Number(inventory.lowerLimit ?? 0)
                        }
                    }
                } catch (e) {
                    console.warn('获取调出仓库存失败:', e)
                }

                // 获取调入仓库存
                try {
                    const inboundRes = await myaxios.get('/api/Inventory/GetInventoryPage', {
                        params: {
                            productCode: product.productCode,
                            warehouseId: transferForm.inboundWarehouseId,
                            pageIndex: 1,
                            pageSize: 10,
                        },
                    })
                    if (inboundRes.data?.code === 200) {
                        const inventoryList = inboundRes.data?.data?.data || []
                        // 从列表中查找匹配的货品（通过productCode或productId）
                        const inventory = inventoryList.find((item: any) =>
                            item.productId === Number(product.productId) ||
                            item.productCode === product.productCode
                        )
                        if (inventory) {
                            inboundStock = Number(inventory.currentStock ?? inventory.inventoryCurrtnumber ?? inventory.currtnumber ?? 0)
                        }
                    }
                } catch (e) {
                    console.warn('获取调入仓库存失败:', e)
                }
            } catch (error) {
                console.error('获取库存失败:', error)
            }
        }

        transferDetails.value.push({
            lineId: `line_${Date.now()}_${Math.random()}`,
            transferDetailId: 0,
            productId: product.productId,
            productName: product.productName,
            productCode: product.productCode,
            specificationModel: product.productUnit || product.specification || '',
            productUnit: product.productUnit || '',
            unitName: product.productspecification || product.productSpecification || product.specification || '',
            productTypeName: product.producttypeName || '',
            outboundCurrentStock: outboundStock,
            inboundCurrentStock: inboundStock,
            transferQuantity: null,
            transferUnitPrice: Number(product.productInmoney ?? 0),
            transferAmount: 0,
            remark: '',
            lowerLimit: lowerLimit,
        })
    }

    productDialogVisible.value = false
    selectedProducts.value = []
    ElMessage.success('添加成功')
}

const handleDetailSelectionChange = (selection: TransferDetailItem[]) => {
    selectedDetailRows.value = selection
}

const removeSelectedDetails = () => {
    if (selectedDetailRows.value.length === 0) {
        ElMessage.warning('请选择要移除的明细')
        return
    }
    const selectedIds = new Set(selectedDetailRows.value.map(d => d.lineId))
    transferDetails.value = transferDetails.value.filter(d => !selectedIds.has(d.lineId))
    selectedDetailRows.value = []
    ElMessage.success('移除成功')
}

const removeDetail = (index: number) => {
    transferDetails.value.splice(index, 1)
    ElMessage.success('移除成功')
}

const updateDetailAmount = (row: TransferDetailItem) => {
    const quantity = Number(row.transferQuantity ?? 0)
    const unitPrice = Number(row.transferUnitPrice ?? 0)
    row.transferAmount = quantity * unitPrice
}

const totalProductKinds = computed(() => transferDetails.value.length)

const totalTransferQuantity = computed(() => {
    return transferDetails.value.reduce((sum, item) => sum + (Number(item.transferQuantity) || 0), 0)
})

const totalTransferAmount = computed(() => {
    return transferDetails.value.reduce((sum, item) => sum + (item.transferAmount || 0), 0)
})

const validateInventory = async (): Promise<boolean> => {
    if (!isWarehouseSelected(transferForm.outboundWarehouseId) || !isWarehouseSelected(transferForm.inboundWarehouseId)) {
        await transferFormRef.value?.validateField(['outboundWarehouseId', 'inboundWarehouseId'])
        return false
    }
    if (transferForm.outboundWarehouseId === transferForm.inboundWarehouseId) {
        ElMessage.warning('入库仓库和出库仓库不能为同一仓库!')
        return false
    }
    if (transferDetails.value.length === 0) {
        ElMessage.warning('请选择货品!')
        return false
    }

    for (const detail of transferDetails.value) {
        const quantity = Number(detail.transferQuantity ?? 0)
        if (quantity <= 0) {
            ElMessage.warning('货品数量必须大于0!')
            return false
        }

        const outboundStock = Number(detail.outboundCurrentStock ?? 0)
        if (quantity > outboundStock) {
            ElMessage.error('库存不足,不允许调拨出库!')
            return false
        }

        const lowerLimit = Number(detail.lowerLimit ?? 0)
        const remainingStock = outboundStock - quantity

        if (remainingStock < lowerLimit) {
            if (remainingStock < 0) {
                ElMessage.error('库存不能低于货品下限,不允许调拨出库!')
                return false
            }

            try {
                await ElMessageBox.confirm(
                    `当前操作库存将低于货品库存下限,是否执行调拨?`,
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
            } catch {
                return false
            }
        }
    }

    return true
}

const handleSave = async () => {
    if (!transferFormRef.value) return
    if (!transferForm.transferNo) {
        await generateTransferNo()
        if (!transferForm.transferNo) {
            ElMessage.warning('请先生成调拨单号')
            return
        }
    }

    const valid = await transferFormRef.value.validate().catch(() => false)
    if (!valid) return

    const inventoryValid = await validateInventory()
    if (!inventoryValid) return

    if (transferDetails.value.length === 0) {
        ElMessage.warning('请至少添加一条调拨明细')
        return
    }

    await nextTick()
    await nextTick()

    transferDetails.value.forEach((item) => {
        let quantity: any = item.transferQuantity
        if (quantity == null || quantity === undefined || quantity === '') {
            quantity = 0
        } else if (typeof quantity !== 'number') {
            quantity = Number(quantity)
            if (isNaN(quantity)) {
                quantity = 0
            }
        }
        item.transferQuantity = quantity

        let unitPrice: any = item.transferUnitPrice
        if (unitPrice == null || unitPrice === undefined || unitPrice === '') {
            unitPrice = 0
        } else if (typeof unitPrice !== 'number') {
            unitPrice = Number(unitPrice)
            if (isNaN(unitPrice)) {
                unitPrice = 0
            }
        }
        item.transferUnitPrice = unitPrice

        if (quantity > 0 && unitPrice > 0) {
            item.transferAmount = quantity * unitPrice
        } else {
            item.transferAmount = 0
        }
    })

    await nextTick()

    const validDetails = transferDetails.value.filter((item) => {
        const quantity = Number(item.transferQuantity)
        if (isNaN(quantity) || !isFinite(quantity) || quantity <= 0) {
            return false
        }
        const unitPrice = Number(item.transferUnitPrice)
        if (isNaN(unitPrice) || !isFinite(unitPrice) || unitPrice <= 0) {
            return false
        }
        return true
    })

    if (validDetails.length === 0) {
        ElMessage.warning('调拨明细不能为空，请至少填写一条有效的明细（调拨数量和调拨单价必须大于0）')
        return
    }

    if (validDetails.length < transferDetails.value.length) {
        ElMessage.warning(`已过滤 ${transferDetails.value.length - validDetails.length} 条无效明细（数量或单价为0），仅保存有效明细`)
    }

    saving.value = true
    try {
        if (isEditMode.value && !currentTransferId.value) {
            ElMessage.error('缺少调拨单ID，无法保存')
            return
        }

        const detailPayload = validDetails.map((item) => ({
            transferDetailId: Number((item as any).transferDetailId || 0),
            productId: Number(item.productId),
            productCode: String(item.productCode || ''),
            productName: String(item.productName || ''),
            specificationModel: String(item.specificationModel || item.productUnit || ''),
            unitName: String(item.unitName || ''),
            transferQuantity: Number(item.transferQuantity),
            inboundPrice: Number(item.transferUnitPrice),
            transferAmount: Number(item.transferAmount),
            remark: String(item.remark || ''),
        }))

        const payload = {
            transferId: isEditMode.value ? Number(currentTransferId.value) : 0,
            transferNo: transferForm.transferNo,
            documentStatus: 0,
            transferApplyDate: transferForm.transferApplicationDate,
            transferTypeId: Number(transferForm.transferTypeId) || 0,
            transferTypeName: transferTypeOptions.value.find((item) => item.value === transferForm.transferTypeId)?.label || '',
            outWarehouseId: Number(transferForm.outboundWarehouseId),
            inWarehouseId: Number(transferForm.inboundWarehouseId),
            handler: transferForm.handler,
            remark: transferForm.remark,
            details: detailPayload,
        }

        const requestUrl = isEditMode.value ? '/api/Transfer/UpdateTransfer' : '/api/Transfer/CreateTransfer'
        const res = await myaxios.post(requestUrl, payload)
        if (res.data?.code === 200) {
            ElMessage.success('保存成功')
            router.push('/GetTransfer')
        } else {
            ElMessage.error(res.data?.message || '保存失败')
        }
    } catch (error: any) {
        console.error('保存失败:', error)
        ElMessage.error(error?.response?.data?.message || '保存失败，请稍后重试')
    } finally {
        saving.value = false
    }
}

const TRANSFER_DICT_NAME = '调拨类型'

const normalizeDictOption = (item: any): TransferTypeOption => ({
    label: item.dictionaryName || item.dictName || item.name || item.label || '未知类型',
    value: Number(item.dictionaryId ?? item.dictId ?? item.id ?? item.value ?? 0),
})

const loadTransferTypeFromDict = async (): Promise<boolean> => {
    try {
        const parentRes = await myaxios.get('/api/Dictionary/GetParentDictionaryList', {
            params: {
                pageindex: 1,
                pagesize: 999,
                dictionaryName: TRANSFER_DICT_NAME,
            },
        })
        const parentList = parentRes?.data?.data?.data ?? []
        const parentDict = parentList.find(
            (item: any) =>
                (item.dictionaryName || item.dictName || item.name) === TRANSFER_DICT_NAME
        )
        const parentId = Number(parentDict?.dictionaryId ?? parentDict?.dictId ?? parentDict?.id ?? 0)
        if (!parentId) return false

        const childRes = await myaxios.get('/api/Dictionary/GetChildDictionaryList', {
            params: {
                parentId,
                pageindex: 1,
                pagesize: 999,
            },
        })
        const childList = childRes?.data?.data?.data ?? []
        const mapped = childList
            .map((item: any) => normalizeDictOption(item))
            .filter((opt: TransferTypeOption) => Boolean(opt.value))
        if (mapped.length) {
            transferTypeOptions.value = mapped
            return true
        }
    } catch (error) {
        console.warn('通过字典获取调拨类型失败', error)
    }
    return false
}

const loadTransferTypeFromLegacy = async (): Promise<boolean> => {
    try {
        const res = await myaxios.get('/api/Transfer/GetTransferType', { params: { pageIndex: 1, pageSize: 200 } })
        const list = res?.data?.data || res?.data?.rows || []
        if (Array.isArray(list) && list.length) {
            transferTypeOptions.value = list
                .map((item: any) => ({
                    label: item.transferTypeName || item.name || item.dictName || '未知类型',
                    value: Number(item.transferTypeId ?? item.id ?? item.value ?? 0),
                }))
                .filter((opt: TransferTypeOption) => opt.value !== 0)
            return transferTypeOptions.value.length > 0
        }
    } catch (error) {
        console.warn('通过旧接口获取调拨类型失败', error)
    }
    return false
}

const loadTransferTypes = async () => {
    let loaded = await loadTransferTypeFromDict()
    if (!loaded) {
        loaded = await loadTransferTypeFromLegacy()
    }
    if (!loaded) {
        transferTypeOptions.value = fallbackTransferTypeOptions
    }
    // 不再自动选中第一项，保持空值以展示“请选择”
}

const resetForm = async () => {
    transferFormRef.value?.clearValidate()
    if (isEditMode.value && currentTransferId.value) {
        await loadTransferDetailForForm(currentTransferId.value)
        return
    }
    if (pageMode.value === 'copy' && copySourceId.value) {
        await loadTransferDetailForForm(copySourceId.value, { isCopy: true })
        return
    }
    clearForm()
}

const goBack = () => {
    router.push('/GetTransfer')
}

onMounted(async () => {
    await Promise.all([loadWarehouses(), loadTransferTypes()])
    await initPage()
})

watch(
    () => ({
        transferId: route.query.transferId,
        copyFrom: route.query.copyFrom,
    }),
    async () => {
        await initPage()
    },
)
</script>

<style scoped>
.common-layout {
    padding: 20px;
}

.card-block {
    margin-bottom: 20px;
}

.card-title {
    font-weight: 600;
    font-size: 16px;
}

.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.detail-actions {
    display: flex;
    gap: 8px;
}

.detail-summary {
    margin-top: 12px;
    display: flex;
    gap: 24px;
    font-size: 14px;
    color: #606266;
}

.readonly-input {
    background-color: #f5f7fa;
}

.product-search-form {
    margin-bottom: 16px;
}

.product-pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

.fixed-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-top: 1px solid #e4e7ed;
    padding: 12px 24px;
    z-index: 1000;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.footer-content {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    max-width: 1200px;
    margin: 0 auto;
}
</style>
